/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.ap.entity.Expenditure;
import com.jeeplus.modules.ap.mapper.ExpenditureMapper;
import com.jeeplus.modules.ap.entity.DetailsExpenditure;
import com.jeeplus.modules.ap.mapper.DetailsExpenditureMapper;

/**
 * 支出Service
 * @author slD
 * @version 2017-11-30
 */
@Service
@Transactional(readOnly = true)
public class ExpenditureService extends CrudService<ExpenditureMapper, Expenditure> {

	@Autowired
	private DetailsExpenditureMapper detailsExpenditureMapper;
	
	public Expenditure get(String id) {
		Expenditure expenditure = super.get(id);
		expenditure.setDetailsExpenditureList(detailsExpenditureMapper.findList(new DetailsExpenditure(expenditure)));
		return expenditure;
	}
	
	public List<Expenditure> findList(Expenditure expenditure) {
		return super.findList(expenditure);
	}
	
	public Page<Expenditure> findPage(Page<Expenditure> page, Expenditure expenditure) {
		return super.findPage(page, expenditure);
	}
	
	@Transactional(readOnly = false)
	public void save(Expenditure expenditure) {
		super.save(expenditure);
		for (DetailsExpenditure detailsExpenditure : expenditure.getDetailsExpenditureList()){
			if (detailsExpenditure.getId() == null){
				continue;
			}
			if (DetailsExpenditure.DEL_FLAG_NORMAL.equals(detailsExpenditure.getDelFlag())){
				if (StringUtils.isBlank(detailsExpenditure.getId())){
					detailsExpenditure.setExpenditure(expenditure);
					detailsExpenditure.preInsert();
					detailsExpenditureMapper.insert(detailsExpenditure);
				}else{
					detailsExpenditure.preUpdate();
					detailsExpenditureMapper.update(detailsExpenditure);
				}
			}else{
				detailsExpenditureMapper.delete(detailsExpenditure);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Expenditure expenditure) {
		super.delete(expenditure);
		detailsExpenditureMapper.delete(new DetailsExpenditure(expenditure));
	}
	
}